#!/usr/bin/perl
use File::Find;
use File::Basename;
use Digest::MD5 qw(md5 md5_hex md5_base64);

#----BEGIN MAIN BLOCK
my $vfilename = time()."-statlist.txt";
my ($totalsize,$filecount,$dircount,$averagesize,$starttime,$endtime);
$starttime=&timer;
my $max=0;
my $min=99999999999;
@ARGV=qw(.) if not @ARGV;

open (OUTFILE,">\.\\$vfilename") or die ("Couldn't open $vfilename for writing\n");
print OUTFILE "\"Path/Filename\",\"Size (Bytes)\",\"Permissions\",\"MTime\",\"ATime\",\"CTime\",\"MD5\"\n";
print "Running recursive STAT on files in:  @ARGV\n";

find(\&dirlist, @ARGV);

if ($filecount!=0){$averagesize=$totalsize/$filecount;}
$endtime=&timer;
my $output="\n--------\nStart time: $starttime
End time: $endtime
Total size: $totalsize Bytes
Total files: $filecount
Average filesize: $averagesize Bytes
Max filesize: $max Bytes
Min filesize: $min Bytes";
print $output;
print "\nDetailed results in $vfilename";
print OUTFILE $output;
close(OUTFILE);

prEnd();
#---END MAIN BLOCK

sub dirlist {
   $fpath=$File::Find::name;
   #$pathfile = $fpath;
   #$pathfile=~s/\\/\//g;
   $fpath=~s/\//\\/g;
   if (-f $fpath){statbot($fpath);}
}

sub statbot{
        my $file = $File::Find::name;
        $file=~s/\//\\/g; #switches /'s with \'s for windows paths
        my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat($file);
	if ($size>$max){$max=$size;}
	if ($size<$min){$min=$size;}
	my $a_time = localtime($atime);
	my $m_time = localtime($mtime);
	my $c_time = localtime($ctime);
	$totalsize=$totalsize+$size;
	$filecount=$filecount+1;
        $digest = md5_hex($file);
	if ($digest != ""){
                printf OUTFILE "\"%s\",%i,\"%04o\",\"%s\",\"%s\",\"%s\"\n",$file,$size,$mode&07777,$m_time,$a_time,$c_time;
                printf "\"%s\",%i,\"%04o\",\"%s\",\"%s\",\"%s\"\n",$file,$size,$mode&07777,$m_time,$a_time,$c_time; 
        } else {
                
		printf OUTFILE "\"%s\",%i,\"%04o\",\"%s\",\"%s\",\"%s\",\"%s\"\n",$file,$size,$mode&07777,$m_time,$a_time,$c_time,$digest;
                printf "\"%s\",%i,\"%04o\",\"%s\",\"%s\",\"%s\",\"%s\"\n",$file,$size,$mode&07777,$m_time,$a_time,$c_time,$digest;
	}
}
sub timer {
my (@months,@weekDays,$totalsize,$filecount,$averagesize,$dircount,$year,$theTime);
my ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings);
@months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
@weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
$year = 1900 + $yearOffset;
$theTime = "$hour:$minute:$second, $weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year";
}